// utils/useDebounce.js
import { onUnmounted } from 'vue'

export const useDebounce = (fn, delay = 300) => {
  let timer = null

  const debounced = (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }

  // 组件卸载时自动清除定时器
  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  })

  return debounced
}